const axios = require('axios');
const redis = require('../config/redis');

class ZhihuService {
  constructor() {
    this.baseURL = process.env.ZHIHU_HOTSEARCH_URL || 'https://api.zhihu.com/topstory/hot-list';
    this.timeout = parseInt(process.env.REQUEST_TIMEOUT) || 10000;
  }

  // 获取知乎热搜数据
  async getHotSearch() {
    const cacheKey = 'zhihu:hotsearch';
    
    return redis.getOrSet(cacheKey, async () => {
      try {
        console.log('Fetching fresh Zhihu hot search data...');
        
        const response = await axios.get(this.baseURL, {
          timeout: this.timeout,
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Referer': 'https://www.zhihu.com/hot',
            'Origin': 'https://www.zhihu.com'
          }
        });

        return this.transformData(response.data);
      } catch (error) {
        console.error('Zhihu API Error:', error.message);
        // 返回模拟数据作为降级方案
        return this.generateMockData();
      }
    }, parseInt(process.env.CACHE_DURATION) || 300);
  }

  // 转换知乎数据格式
  transformData(data) {
    if (!data || !data.data) {
      return this.generateMockData();
    }

    return data.data.map((item, index) => {
      // 使用真实的标题而不是硬编码
      let title = item.target?.title || item.target?.question?.title || item.title || `知乎热搜 ${index + 1}`;
      let heatValue = 1000;
      
      try {
        if (item.detail_text) {
          // 从detail_text中提取热度信息，例如"581 万热度"
          const detailMatch = item.detail_text.match(/(\d+(\.\d+)?)\s*万/);
          if (detailMatch) {
            heatValue = parseFloat(detailMatch[1]) * 10000;
          } else {
            const numMatch = item.detail_text.match(/(\d+)/);
            if (numMatch) {
              heatValue = parseInt(numMatch[1]) * 1000;
            }
          }
        }
      } catch (error) {
        console.error('Error parsing Zhihu data:', error.message);
      }

      return {
        id: `zhihu_${item.id || index}`,
        title: title,
        description: item.detail_text || '热门话题',
        platform: '知乎',
        views: this.formatHeat(heatValue),
        comments: Math.round(heatValue / 100),
        heat: this.calculateHeat(heatValue),
        trend: this.calculateTrend(item),
        updatedAt: new Date().toISOString(),
        url: item.target?.url || item.url || 'https://www.zhihu.com/hot',
        tags: this.extractTags(item),
        rank: index + 1,
        isAd: item.card_label !== undefined,
        note: item.detail_text || ''
      };
    }).slice(0, 50);
  }

  // 格式化热度显示
  formatHeat(score) {
    if (score >= 1000000) {
      return `${(score / 1000000).toFixed(1)} 万热度`;
    } else if (score >= 1000) {
      return `${(score / 1000).toFixed(1)} 千热度`;
    }
    return `${score} 热度`;
  }

  // 计算热度值
  calculateHeat(score) {
    const maxScore = 5000000; // 知乎热度通常较高
    const heat = Math.min(100, Math.round((score / maxScore) * 100));
    return Math.max(heat, 10);
  }

  // 计算趋势
  calculateTrend(item) {
    // 根据热度变化计算趋势
    if (item.hot_score_change) {
      return item.hot_score_change > 0 ? 5 : -5;
    }
    return Math.floor(Math.random() * 10) - 5;
  }

  // 提取标签
  extractTags(item) {
    const tags = [];
    
    if (item.is_commercial) {
      tags.push('广告');
    }
    
    if (item.is_activity) {
      tags.push('活动');
    }
    
    if (item.is_recommend) {
      tags.push('推荐');
    }
    
    return tags.length > 0 ? tags : ['热门'];
  }

  // 生成模拟数据（降级方案）
  generateMockData() {
    console.log('Generating mock Zhihu hot search data...');
    
    const mockTopics = [
      {
        id: 'zhihu_1',
        title: '如何看待人工智能的快速发展？',
        description: '人工智能技术日新月异，对社会产生深远影响',
        platform: '知乎',
        views: '285 万热度',
        comments: 1245,
        heat: 95,
        trend: 8,
        updatedAt: new Date().toISOString(),
        url: 'https://www.zhihu.com/question/123456',
        tags: ['科技', '热门'],
        rank: 1,
        isAd: false,
        note: ''
      },
      {
        id: 'zhihu_2',
        title: '有哪些值得推荐的书籍？',
        description: '分享你读过的好书',
        platform: '知乎',
        views: '182 万热度',
        comments: 892,
        heat: 88,
        trend: 5,
        updatedAt: new Date().toISOString(),
        url: 'https://www.zhihu.com/question/234567',
        tags: ['文化', '推荐'],
        rank: 2,
        isAd: false,
        note: ''
      },
      {
        id: 'zhihu_3',
        title: '如何提高工作效率？',
        description: '分享高效工作的方法和技巧',
        platform: '知乎',
        views: '156 万热度',
        comments: 673,
        heat: 82,
        trend: 3,
        updatedAt: new Date().toISOString(),
        url: 'https://www.zhihu.com/question/345678',
        tags: ['职场', '技巧'],
        rank: 3,
        isAd: false,
        note: ''
      },
      {
        id: 'zhihu_4',
        title: '最近有什么好看的电影？',
        description: '推荐近期上映的优秀电影',
        platform: '知乎',
        views: '134 万热度',
        comments: 456,
        heat: 76,
        trend: -2,
        updatedAt: new Date().toISOString(),
        url: 'https://www.zhihu.com/question/456789',
        tags: ['影视', '推荐'],
        rank: 4,
        isAd: false,
        note: ''
      },
      {
        id: 'zhihu_5',
        title: '这款产品值得购买吗？',
        description: '某品牌最新产品评测',
        platform: '知乎',
        views: '112 万热度',
        comments: 234,
        heat: 71,
        trend: -4,
        updatedAt: new Date().toISOString(),
        url: 'https://www.zhihu.com/question/567890',
        tags: ['购物', '广告'],
        rank: 5,
        isAd: true,
        note: '广告'
      }
    ];

    return mockTopics;
  }

  // 获取单个热点详情
  async getHotspotDetail(id) {
    const allData = await this.getHotSearch();
    const hotspot = allData.find(item => item.id === id);
    
    if (!hotspot) {
      throw new Error('热点不存在');
    }

    // 生成模拟趋势数据
    const trendData = this.generateTrendData(hotspot.heat);
    
    return {
      hotspot,
      trendData
    };
  }

  // 生成趋势数据
  generateTrendData(baseHeat) {
    const now = new Date();
    const data = [];
    
    for (let i = 11; i >= 0; i--) {
      const time = new Date(now.getTime() - i * 2 * 60 * 60 * 1000);
      const hour = time.getHours().toString().padStart(2, '0');
      const minute = '00';
      
      // 模拟热度波动
      const fluctuation = Math.random() * 10 - 5;
      const heat = Math.max(10, Math.min(100, baseHeat + fluctuation));
      
      data.push({
        time: `${hour}:${minute}`,
        heat: Math.round(heat)
      });
    }
    
    return data;
  }
}

module.exports = new ZhihuService();